<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/3/16
 * Time: 16:51
 */

namespace app\api\model;


use traits\model\SoftDelete;

class Product extends BaseModel
{
    protected $hidden = ['pivot','update_time','create_time','from','delete_time'];
    protected $autoWriteTimestamp = true;  // 开启模型写入数据库时的自动记录写入时间
    use SoftDelete;  // 引用软删除
    protected $deleteTime = 'delete_time';

    //关联到product_image 一对多
    public function imgs(){
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    //关联到product_property 一对多
    public function properties(){
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    //处理图片url
    public function getMainImgUrlAttr($value, $date){
        return $this->prefixImgUrl($value, $date);
    }

    //查询最新商品
    public static function getMostRecent($count){
        $products = self::limit($count)
            ->order('create_time desc')
            ->select();
        return $products;
    }

    //通过category的id查询分类商品
    public static function getProductByCategory($id){
        $products = self::where('category_id','=',$id)
            ->order('create_time desc')
            ->select();
        return $products;
    }

    //查询单个商品详情
    public static function getProductDetail($id){
        $product = self::with([
            'imgs' => function($query){
                $query->with(['imgUrl'])
                    ->order('order', 'asc');
            }
        ])
            ->with(['properties'])
            ->find($id);
        return $product;
    }

    // 获取商品分页数据
    public static function getSummaryByPage($page = 1, $size = 20){
        $pagingDate = self::order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
        return $pagingDate;
    }
}